using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace X.Ray.Core.Framework
{
    /// <summary>
    /// Author:					Joe Audette
    /// Created:				2007-07-12
    /// Last Modified:			2007-07-12
    /// 
    ///				
    /// The use and distribution terms for this software are covered by the 
    /// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
    /// which can be found in the file CPL.TXT at the root of this distribution.
    /// By using this software in any fashion, you are agreeing to be bound by 
    /// the terms of this license.
    ///
    /// You must not remove this notice, or any other, from this software.
    /// </summary>
    public static class ExportHelper
    {

        public static void ExportDataTableToCSV(
            HttpContext Context, 
            DataTable Table, 
            string Filename)
	    {

		    Context.Response.Clear();
		    Context.Response.Buffer = true;
		    Context.Response.ContentType = "text/csv";

		    Context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + Filename);
		    Context.Response.Charset = "";

		    StreamWriter sw = new StreamWriter(Context.Response.OutputStream);
		    
		    int iColCount = Table.Columns.Count;
		    int i;
		    for (i = 0; i <= iColCount - 1; i++) {
			    sw.Write(Table.Columns[i]);
			    if (i < iColCount - 1)
			    {
				    sw.Write(",");
			    }
		    }
		    sw.Write(sw.NewLine);

		    i = 0;

		    foreach (DataRow row in Table.Rows) {

			    for (i = 0; i <= iColCount - 1; i++) {
				    if (!Convert.IsDBNull(row[i]))
				    {
					    sw.Write("\"");
					    sw.Write(row[i].ToString());
					    sw.Write("\"");
				    }
				    else
				    {
					    sw.Write("");
				    }
				    if (i < iColCount - 1)
				    {
					    sw.Write(",");
				    }
			    }
			    sw.Write(sw.NewLine);
		    }
		    sw.Close();

		    Context.Response.End();

	    }

    }
}
